package com.controller;

import com.dao.AddFriendDao;
import com.dao.ChatDao;
import com.dao.InboxDao;
import com.po.FriendList;
import com.po.InBox;
import com.po.User;
import com.po.chat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Stack;

@WebServlet({"/myFriends", "/addFriends", "/selectFriend", "/friend/myInbox", "/requestAdd",
        "/chatFriends", "/sendMessage"})

public class FriendSystem extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String servletPath = request.getServletPath();
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("id") != null) {
            if ("/myFriends".equals(servletPath)) {
                doSelectFriends(request, response);
            } else if ("/addFriends".equals(servletPath)) {
                doAddFriends(request, response);
            } else if ("/selectFriend".equals(servletPath)) {
                doFriend(request, response);
            } else if ("/friend/myInbox".equals(servletPath)) {
                doSelectInbox(request, response);
            } else if ("/requestAdd".equals(servletPath)) {
                doRequestAdd(request, response);
            } else if ("/chatFriends".equals(servletPath)) {
                doChat(request, response);
            } else if ("/sendMessage".equals(servletPath)) {
                doSend(request, response);
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }

    /**
     * 发送好友请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doSend(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String content = request.getParameter("content");
        HttpSession session = request.getSession(false);
        int id = (int) session.getAttribute("id");
        int user_id = Integer.parseInt(request.getParameter("user_id"));
        if (content.length()>=1) {
            InboxDao.inboxTip(id,user_id,"message",null);
            FriendList.sendMessage(id, user_id, content);
            request.getRequestDispatcher("/chatFriends?user_id=" + user_id).forward(request, response);
        }else{
            request.getRequestDispatcher("/chatFriends?user_id=" + user_id).forward(request, response);
        }
    }

    private void doChat(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        int id = (int) session.getAttribute("id");
        int user_id = Integer.parseInt(request.getParameter("user_id"));

        AddFriendDao.deleteAdd(user_id, id, "message");
        Stack<chat> friendChat = ChatDao.getFriendChat(id, user_id);

        request.setAttribute("friendChat", friendChat);
        request.setAttribute("user", FriendList.getUser(user_id));
        request.getRequestDispatcher("/friend/friendChat.jsp").forward(request, response);
    }

    private void doRequestAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession(false);
        int id = (int) session.getAttribute("id");
        String state = request.getParameter("state");
        int user_id = Integer.parseInt(request.getParameter("user_id"));

        if ("accept".equals(state)) {
            AddFriendDao.addFriend(id, user_id);
            AddFriendDao.addFriend(user_id, id);
            InboxDao.deleteAdd(id, user_id, "add");
            InboxDao.deleteAdd(user_id, id, "add");
            response.sendRedirect(request.getContextPath() + "/friend/myInbox");
        } else if ("refuse".equals(state)) {
            InboxDao.deleteAdd(id, user_id, "add");
            InboxDao.deleteAdd(user_id, id, "add");
            response.sendRedirect(request.getContextPath() + "/friend/myInbox");
        } else if ("thank".equals(state)) {
            InboxDao.InsertThanks(id, user_id, "thank");
            InboxDao.deleteAdd(id, user_id, "praise");
            InboxDao.deleteAdd(user_id, id, "praise");
            response.sendRedirect(request.getContextPath() + "/friend/myInbox");
        } else if ("know".equals(state)) {
            InboxDao.deleteAdd(id, user_id, "thank");
            InboxDao.deleteAdd(user_id, id, "thank");
            response.sendRedirect(request.getContextPath() + "/friend/myInbox");
        }else if("note".equals(state)){
            InboxDao.deleteAdd(user_id,id,"note");
            response.sendRedirect(request.getContextPath() + "/friend/myInbox");
        }
    }

    private void doSelectInbox(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        int id = (int) session.getAttribute("id");

        List<InBox> myNote = InboxDao.getMyNote(id);
        request.setAttribute("myNote", myNote);
        request.getRequestDispatcher("/friend/myInbox.jsp").forward(request, response);
    }

    private void doFriend(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean success = true;
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(false);
        int id = (int) session.getAttribute("id");
        int user_name = (Integer.parseInt(request.getParameter("user_name")));
        List<User> friends = FriendList.getFriends(id);
        List<Integer> aLl = FriendList.getALl(id);
        if (!aLl.contains(user_name)) {
            out.print("查无此人");
        } else {
            for (User user : friends) {
                if (user_name == user.getId()) {
                    success = false;
                    break;
                }
            }
            if (success) {
                User information = FriendList.getUser(user_name);
                if (FriendList.selectInbox(id, information.getId())) {
                    FriendList.addFriendsInbox(id, information.getId());
                    out.println("对方是：" + information.getName() + information.getSex());
                    out.println("请求发送成功，等待对方通过");
                } else {
                    out.print("已经添加，请等待对方通过");
                }
            } else {
                out.println("对方已经是你的好友了，不用重复添加");
            }
        }
    }

    private void doAddFriends(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("id");
        String user_name = request.getParameter("user_name");

        User information = FriendList.getInformation(user_name);

        if (FriendList.selectInbox(id, information.getId())) {
            FriendList.addFriendsInbox(id, information.getId());
            out.print("请求成功，请耐心等待对方通过");
            out.println("<a href=\"" + request.getContextPath() + "/function/openEnvelope\">返回信封区</a>");
        } else {
            out.print("你已经添加了，请等待对方的同意");
            out.println("<a href=\"" + request.getContextPath() + "/function/openEnvelope\">返回信封区</a>");
        }
    }

    private void doSelectFriends(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession(false);
        int id = (int) session.getAttribute("id");

        List<User> friends = FriendList.getFriends(id);

        request.setAttribute("friends", friends);
        request.getRequestDispatcher("/friend/MyFriends.jsp").forward(request, response);
    }
}
